#include "main_config.h"
#include "timer.h"
#include "GPIO_INIT.h"

void TIMx_init(u16 per,u16 psc,TIM_TypeDef* TIM_x){
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	
	RCC_APB1PeriphClockCmd((uint32_t)(1<<(((uint32_t)TIM_x-APB1PERIPH_BASE)>>10)),ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);

	TIM_TimeBaseInitStruct.TIM_Period=per;
	TIM_TimeBaseInitStruct.TIM_Prescaler=psc;
	TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseInit(TIM_x,&TIM_TimeBaseInitStruct );
}

void TIMx_OCx_init(TIM_TypeDef* TIM_x,u8 OCx,GPIO_TypeDef* GPIOx,uint16_t GPIO_Pin_x){
	TIM_OCInitTypeDef TIM_OCInitStruct;
	
	TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High;	
	TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
	
	GPIO_init(GPIOx,GPIO_Pin_x,GPIO_Mode_AF_PP);
	
	switch(OCx){
		case 1:
			TIM_OC1Init(TIM_x,&TIM_OCInitStruct);
			TIM_OC1PreloadConfig(TIM_x,TIM_OCPreload_Enable);
			break;
		case 2:
			TIM_OC2Init(TIM_x,&TIM_OCInitStruct);
			TIM_OC2PreloadConfig(TIM_x,TIM_OCPreload_Enable);
			break;
		case 3:
			TIM_OC3Init(TIM_x,&TIM_OCInitStruct);
			TIM_OC3PreloadConfig(TIM_x,TIM_OCPreload_Enable);
			break;
		case 4:
			TIM_OC4Init(TIM_x,&TIM_OCInitStruct);
			TIM_OC4PreloadConfig(TIM_x,TIM_OCPreload_Enable);
			break;
	}
}

/*
	时钟中断
	TIM_IT_Update
	TIM_IT_CC1
	TIM_IT_CC2
	TIM_IT_CC3
	TIM_IT_CC4
	TIM_IT_COM
	TIM_IT_Trigger
	TIM_IT_Break 
*/
void TIMx_NVIC_init(TIM_TypeDef* TIM_x,uint16_t TIM_IT_x,IRQn_Type TIMx_IRQn){
	NVIC_InitTypeDef NVIC_InitStruct;
	
	//中断优先级管理
	TIM_ITConfig(TIM_x,TIM_IT_x,ENABLE);
	NVIC_InitStruct.NVIC_IRQChannel=TIMx_IRQn;	
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=2;	
	NVIC_InitStruct.NVIC_IRQChannelSubPriority=2;
	NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;	
	NVIC_Init(&NVIC_InitStruct);

	TIM_Cmd(TIM_x,DISABLE);
}


